import http from 'http';
import { Server } from "socket.io";
import jwt from 'jsonwebtoken';
import md5 from 'md5'

//在线用户
const users = {}
//未读消息列表
let messageList = []

export default function (app) {
  const server = http.createServer(app);
  const io = new Server(server,{ cors:true });
  io.on("connection", (socket) => {
    const { auth,query } = socket.handshake
    if(!auth.token){
      socket.emit('error',{ code:401,msg:'未登录',data:{ message:'未传入token' } })
      io.close()
    }
    //校验身份(获取到用户id)
    const { id } = jwt.verify(auth.token.replace(/Bearer /,''),process.env.SecretKey)
    if(!id){
      socket.emit('error',{ code:401,msg:'连接失败',data:{ message:'登录超时' } })
      io.close()
    }
    const { to,from } = query
    if(!to || !from){
      socket.emit('error',{ code:400,msg:'连接失败',data:{ message:'参数错误' } })
       io.close()
    }
    const userId = md5(parseInt(id))
    //用户ID和socket一同存入在线用户列表
    users[userId] = socket
    //查看接收方是否在线
    //发送方ID 
    const senderId = md5(parseInt(from))
    //接收方ID
    const recieverId = md5(parseInt(to)) 
    if(users[recieverId]){
      users[recieverId].emit('/chat/status',{ code:200,msg:'请求成功',data:{ code:1,status:'在线' }  })
    } 
    //查找接收方是否有未读消息
    const list = messageList.filter(item=>item.to == id)
    //如果有未读消息则推送消息
    if(list.length){
        list.forEach(item=>{
          users[userId].emit('message',item)
        })
        //移除已推送至用户的消息
       messageList = messageList.filter(item=>item.to != id)
    }
    socket.on('message',async(data)=>{
      //  const { to,from } = data
        //取出用户信
      //  const recieverId = md5(to) 
       //如果对方在线发送给接受者
       if(users[recieverId]){
         users[recieverId].emit('message',data)
       }else{
         //如果不在线推送至未读列表
         if(messageList.length > 10) return 
         messageList.push(data)
       }
    })
    socket.on('disconnect',()=>{
      //离线后从列表删除
      delete users[userId];
      if(users[recieverId]){
        users[recieverId].emit('/chat/status',{ code:200,msg:'请求成功',data:{ code:0,status:'离线' }  })
      }
    })
  });


  return server
}
